<template>
  <pro-layout
    :menus='menus'
    :collapsed='collapsed'
    :mediaQuery='query'
    :isMobile='isMobile'
    :handleMediaQuery='handleMediaQuery'
    :handleCollapse='handleCollapse'
    :i18nRender='i18nRender'
    v-bind='settings'
  >
    <template v-slot:menuHeaderRender>
      <div>
        <img src='@/assets/jx-logo.png'  alt='logo'/>
        <h1 style='margin-left: 0;'>{{ title }}</h1>
      </div>
    </template>
    
    <!--<template v-slot:headerContentRender>
      <div>
        <a-tooltip title='刷新页面'>
          <a-icon type='reload' style='font-size: 18px;cursor: pointer;' @click='reload()' />
        </a-tooltip>
      </div>
    </template>-->
    
    <!--TODO 设置的抽屉-->
    <!--<setting-drawer v-if='isDev' :settings='settings' @change='handleSettingChange'>
    
    </setting-drawer>-->
    
    
    <template v-slot:rightContentRender>
      <right-content :top-menu="settings.layout === 'topmenu'" :is-mobile='isMobile' :theme='settings.theme' />
    </template>
    <!-- custom footer / 自定义Footer -->
    <template v-slot:footerRender>
      <global-footer />
    </template>
    <router-view />
  </pro-layout>
</template>

<script>
// import SettingDrawer from '@/components/SettingDrawer'
// import { SettingDrawer, updateTheme } from '@ant-design-vue/pro-layout'
import { SettingDrawer, updateTheme } from '@ant-design-vue/pro-layout'
import { i18nRender } from '@/locales'
import { mapState } from 'vuex'
import { CONTENT_WIDTH_TYPE, SIDEBAR_TYPE, TOGGLE_MOBILE_TYPE } from '@/store/mutation-types'

import defaultSettings from '@/config/defaultSettings'
import RightContent from '@/components/GlobalHeader/RightContent'
import GlobalFooter from '@/components/GlobalFooter'
import Ads from '@/components/Other/CarbonAds'

export default {
  name: 'BasicLayout',
  components: {
    SettingDrawer,
    RightContent,
    GlobalFooter,
    Ads
  },
  data() {
    return {
      
      websocketNotice: null,
      // preview.pro.antdv.com only use.
      isProPreviewSite: process.env.VUE_APP_PREVIEW === 'true' && process.env.NODE_ENV !== 'development',
      // end
      isDev: process.env.NODE_ENV === 'development' || process.env.VUE_APP_PREVIEW === 'true',
      
      // base
      menus: [],
      // 侧栏收起状态
      collapsed: true,
      title: defaultSettings.title,
      settings: {
        // 布局类型
        layout: defaultSettings.layout, // 'sidemenu', 'topmenu'
        // CONTENT_WIDTH_TYPE
        contentWidth: defaultSettings.layout === 'sidemenu' ? CONTENT_WIDTH_TYPE.Fluid : defaultSettings.contentWidth,
        // 主题 'dark' | 'light'
        theme: defaultSettings.navTheme,
        // 主色调
        primaryColor: defaultSettings.primaryColor,
        fixedHeader: defaultSettings.fixedHeader,
        fixSiderbar: defaultSettings.fixSiderbar,
        colorWeak: defaultSettings.colorWeak,
        
        hideHintAlert: false,
        hideCopyButton: false
      },
      // 媒体查询
      query: {},
      
      // 是否手机模式
      isMobile: false
    }
  },
  computed: {
    ...mapState({
      // 动态主路由
      mainMenu: state => state.permission.addRouters
    })
  },
  created() {
    
    const routes = this.mainMenu.find(item => item.path === '/')
    this.menus = (routes && routes.children) || []
    // 处理侧栏收起状态
    this.$watch('collapsed', () => {
      this.$store.commit(SIDEBAR_TYPE, this.collapsed)
    })
    this.$watch('isMobile', () => {
      this.$store.commit(TOGGLE_MOBILE_TYPE, this.isMobile)
    })
    // 尝试连接websocket
    try {
      this.webSocketService()
    } catch (e) {
      console.log(e)
    }
    
  },
  mounted() {
    
    const userAgent = navigator.userAgent
    if (userAgent.indexOf('Edge') > -1) {
      this.$nextTick(() => {
        this.collapsed = !this.collapsed
        setTimeout(() => {
          this.collapsed = !this.collapsed
        }, 16)
      })
    }
    
    // first update color
    // TIPS: THEME COLOR HANDLER!! PLEASE CHECK THAT!!
    /*if (process.env.NODE_ENV !== 'production' || process.env.VUE_APP_PREVIEW === 'true') {
      updateTheme(this.settings.primaryColor)
    }*/
  },
  methods: {
    i18nRender,
    handleMediaQuery(val) {
      this.query = val
      if (this.isMobile && !val['screen-xs']) {
        this.isMobile = false
        return
      }
      if (!this.isMobile && val['screen-xs']) {
        this.isMobile = true
        this.collapsed = false
        this.settings.contentWidth = CONTENT_WIDTH_TYPE.Fluid
        // this.settings.fixSiderbar = false
      }
    },
    
    // 刷新页面
    reload() {
      window.location.reload()
    },
    // 修改侧边栏状态
    handleCollapse(val) {
      this.collapsed = val
    },
    // 全局设置
    handleSettingChange({ type, value }) {
      console.log('type', type, value)
      type && (this.settings[type] = value)
      switch (type) {
        case 'contentWidth':
          this.settings[type] = value
          break
        case 'layout':
          if (value === 'sidemenu') {
            this.settings.contentWidth = CONTENT_WIDTH_TYPE.Fluid
          } else {
            this.settings.fixSiderbar = false
            this.settings.contentWidth = CONTENT_WIDTH_TYPE.Fixed
          }
          break
      }
    },
    
    
    webSocketService() {
      /*// 连接地址
      const that = this
      let token = this.$store.getters.token
      
      // TODO 修改websocket地址
      let socketUrl = process.env.VUE_APP_WS_BASE_URL + token
      if (typeof WebSocket == 'undefined') {
        that.openNotification('提示', 5, 400, '0', '当前浏览器无法接收实时报警信息，请使用谷歌/Edge浏览器！')
      } else {
        this.websocketNotice = new WebSocket(socketUrl)
        // 监听socket打开
        this.websocketNotice.onopen = function() {
          console.log('浏览器WebSocket已打开')
        }
        // 监听socket消息接收
        this.websocketNotice.onmessage = function(messageBody) {
          // 转换为json对象
          const jsonMsg = JSON.parse(messageBody.data)
          /// console.log(jsonMsg)
          // 输出消息
          that.openNotification(
            jsonMsg.title,
            jsonMsg.duration,
            jsonMsg.width,
            jsonMsg.level,
            jsonMsg.htmlContent)
        }
        // 监听socket错误
        this.websocketNotice.onerror = function() {
          that.openNotification('错误', 5, 400, '2', '服务器异常,WebSocket连接失败无法接收实时报警信息, 请联系管理员')
        }
        // 监听socket关闭
        this.websocketNotice.onclose = function() {
          console.log('WebSocket已关闭')
        }
      }*/
    },
    
    /**
     * 消息通知
     * @param title       标题
     * @param duration    显示时间
     * @param width       宽度
     * @param level       程度
     * @param htmlContent 内容
     */
    openNotification(title, duration = 5, width = 640, level, htmlContent) {
      let icon = null
      if (duration === -1) {
        duration = null
      }
      
      if (level === '0') {
        icon = <a-icon type='info-circle' theme='twoTone' />
      } else if (level === '1') {
        icon = <a-icon type='stop' theme='twoTone' />
      } else {
        icon = <a-icon type='warning' theme='filled' style='color: #ff0000' />
      }
      
      const key = `open${Date.now()}1`
      this.$notification.open({
        duration,
        message: title,
        style: {
          width: width + 'px',
          marginLeft: `${335 - width}px`
        },
        icon: icon,
        description: h('div', null, [
          h('p', { domProps: { innerHTML: htmlContent } }, null)
        ]),
        btn: h => {
          return h(
            'a-button',
            {
              props: {
                type: 'primary',
                size: 'small'
              },
              on: {
                click: () => this.$notification.close(key)
              }
            },
            '确认'
          )
        },
        key,
        onClose: () => {
        }
      })
    }
  }
}
</script>

<style lang='less'>
@import "./BasicLayout.less";
</style>
